import React from "react";
import {Button} from "antd";
import {toJS} from 'mobx';
import defaultOpts from "./defaultData";
import OptionItem from "./Item";
import "./index.less";
import {OTHER} from "../../../constants/form";
import _u from '../../../utils';
import {WeaLocaleProvider} from "ecCom";
import {SortableContainer} from 'react-sortable-hoc';
import BatchEdit from "./BatchEdit";

const getLabel = WeaLocaleProvider.getLabel;

export default class OptionContent extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    const { options, onChange } = this.props;

    return (
      <Content ecId={`${this && this.props && this.props.ecId || ''}_Content@5qw4cc`}
        {...this.props}
        axis='y'
        shouldCancelStart={val => {
          if (val.target.className !== 'anticon anticon-bars'){
            return true;
          }
        }}
        getHelperDimensions={() => {
          return {width:300,height:30}
        }}
        onSortEnd={({oldIndex, newIndex}) => {
          const newOptions = _u.arrayMove(toJS(options),oldIndex,newIndex);
          onChange(newOptions)
        }}
      />
    )
  }
}

@SortableContainer
class Content extends React.Component {
  constructor(props) {
    super();

    const { options } = props;
    this.state = {
      options,
      index: this.getMaxOptionIndex(options),
      hasOther: options.find(opt => OTHER === opt.key),
      batchEditing: false,
      isInit: _u.isEqual(toJS(options), defaultOpts)
    };
  }

  componentWillReceiveProps(nextProps) {
    const { multi } = nextProps;
    const { options } = this.state;
    const hasOther = options.find(opt => OTHER === opt.key);

    this.setState({options: nextProps.options});
    if(multi !== this.props.multi) {
      let index = null;

      if(!multi) {
        options.forEach((opt, i) => {
          if(opt.selected && index === null) {
            index = i;
          } else {
            opt.selected = false;
          }
        });
      }

      this.setState({ multi });
      this.onOptionsChange(options);
    }

    this.setState({ hasOther });
  }

  onOptionAdd(isOther) {
    const { options, index } = this.state;
    const newIndex = index + 1;

    if(isOther) {
      options.push({
        key: OTHER,
        showname: getLabel('502267','其他') ,
        selected: false
      });
    } else {
      options.push({
        key: String(newIndex),
        showname: ``,
        selected: false
      });

      this.setState({
        index: newIndex
      });
    }

    this.onOptionsChange(options);
  }

  onOptionRemove = opt => {
    const index = this.findOptionIndex(opt.key);
    const { options } = this.state;

    options.splice(index, 1);
    this.onOptionsChange(options);
  }

  onOptionChange = item => {
    const { multi } = this.props;
    const { options } = this.state;
    const index = this.findOptionIndex(item.key);

    options[index] = item;

    if(!multi) {
      options.forEach((opt, i) => {
        if (i !== index) {
        	opt.selected = item.selected ? false : opt.selected;
        }
      });
    }

    this.onOptionsChange(options);
  }

  onOptionsChange(options) {
    this.setState({ options });
    this.props.onChange(options);
  }

  addNormalOption = () => {
    this.onOptionAdd(false);
  }

  addOtherOption = () => {
    this.onOptionAdd(true);
  }

  onBatchEditSave = (value) => {
    const { options, isInit, index } = this.state;
    const hasOther = options.find(opt => OTHER === opt.key);

    let baseIndex = isInit ? 0 : index;
    const names = value.split("\n");
    const optionsNew = isInit ? [] : options.filter(opt => OTHER !== opt.key);
    names.forEach((name) => {
      if (name) {
        baseIndex++;
        optionsNew.push({
          key: String(baseIndex),
          showname: name,
          selected: false
        });
      }
    });

    this.setState({
      index: baseIndex
    });
    hasOther && optionsNew.push(hasOther);

    this.setState({optionsNew});
    this.props.onChange(optionsNew);
    this.setBatchEditVisible(false);
  }

  setBatchEditVisible = (visible) => {
    this.setState({
      batchEditing: visible
    });
  }

  findOptionIndex(key) {
    return this.state.options.findIndex(opt => opt.key === key);
  }

  getMaxOptionIndex(options) {
    let max = 0;
    options.forEach((opt) => {
      if (parseInt(opt.key) > max) {
        max = parseInt(opt.key);
      }
    });
    return parseInt(max);
  }

  render() {
    const { options, hasOther, batchEditing, isInit } = this.state;

    return (
      <div className='wea-edc-opt-content'>
        <div style={{ textAlign: 'right', paddingTop: 5, marginTop: -25, zIndex: 5, position: 'relative' }}>
          {<a onClick={() => this.setBatchEditVisible(true)}>{isInit ? getLabel('511649','批量编辑') : getLabel('511656','批量增加')}</a>}
        </div>
        {options.map((opt,index) => (
          <OptionItem ecId={`${this && this.props && this.props.ecId || ''}_OptionItem@8eq2tj@${index}`}
            key={opt.key}
            item={opt}
            index={index}
            onRemove={this.onOptionRemove}
            onChange={this.onOptionChange}
          />
        ))}
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h67qol`} icon='plus' onClick={this.addNormalOption}>
          <span>{getLabel('502268','添加选项') }</span>
        </Button>
        <div style={{ textAlign: 'right', paddingTop: 5 }}>
          {hasOther ? null : <a onClick={this.addOtherOption}>{getLabel('502269','添加其他') }</a>}
        </div>

        <BatchEdit ecId={`${this && this.props && this.props.ecId || ''}_BatchEdit@d4llsb`}
          visible={batchEditing}
          onVisibleChange={this.setBatchEditVisible}
          onSave={this.onBatchEditSave}
          options={isInit ? options : null}
        />
      </div>
    );
  }
}

OptionContent.defaultProps = {
  multi: false,
  options: defaultOpts,
  onChange: () => { }
};